"""
一个线程需要在一个“消费者”线程处理完特定的数据项时立即得到通知
"""

from queue import Queue
from threading import Thread, Event
import time


# Object that signals shutdown
_sentinel = object()

# A thread that produces data
def producer(out_q):
    n = 10
    while n > 0:
        # Make an (data, event) pair and hand it to the consumer
        evt = Event()
        out_q.put((n, evt))
        print('Put:', n)
        
        time.sleep(1)
        n -= 1
        evt.wait()


    # Put the sentinel on the queue to indicate completion
    out_q.put((_sentinel, Event()))
    print('Producer shutting down')

# A thread that consumes data
def consumer(in_q):
    while True:
        # Get some data
        data, evt = in_q.get()

        # Check for termination
        if data is _sentinel:
            in_q.put((_sentinel, Event())) # 关闭其他消费者
            break

        # Process the data
        print('Got:', data)
        time.sleep(1.2)

        evt.set()

    print('Consumer shutting down')

def recipe1():
    q = Queue()
    t1 = Thread(target=consumer, args=(q,))
    t2 = Thread(target=producer, args=(q,))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

def main():
    print('recipe1'.center(20, '*'))
    recipe1()



if __name__ == '__main__':
    main()       